using System;
using Microsoft.Extensions.DependencyInjection;

namespace AspNetCoreExtension
{
    /// <summary>
    /// 依赖IOC容器的通用范型懒加载
    /// </summary>
    /// <typeparam name="T">懒加载组件类型</typeparam>
    /// <seealso cref="System.Lazy{T}" />
    public class DILazy<T> : Lazy<T> where T : class
    {
        public DILazy(IServiceProvider provider) : base(() => provider.GetRequiredService<T>()) { }
    }

    public static class LazySupportDIExtensions
    {
        /// <summary>
        /// 增加易逝的生命周期懒加载组件
        /// </summary>
        /// <param name="services">The services.</param>
        public static void AddLazySupport(this IServiceCollection services)
        {
            services.AddTransient(typeof(Lazy<>), typeof(DILazy<>));
        }
    }
}
